import logging
import os
from django.conf import settings
from django.template import loader

from celery_tasks.main import app
from goods.models import SKU
from goods.utils import get_categories

# 商品详情页
@app.task(name='generate_static_sku_detail_html')
def generate_static_sku_detail_html(sku_id):
    '''静态页面的详情化'''
    # 商品分类菜单
    categories = get_categories()
    # sku信息
    sku = SKU.objects.get(id=sku_id)
    sku.images = sku.skuimage_set.all()
    # 面包屑导航
    goods = sku.goods
    goods.channel = goods.category1.goodschannel_set.all()[0]
    logger = logging.getLogger('django')
    logger.info(goods.channel, '---------')

    # 构造商品规格
    sku_specs = sku.skuspecification_set.order_by('spec_id')
    sku_key = []
    for spec in sku_specs:
        sku_key.append(spec.option.id)

    skus = goods.sku_set.all()


    spec_sku_map = {}
    for s in skus:
        s_specs = s.skuspecification_set.order_by('spec_id')
        key = []
        for specs in s_specs:
            key.append(specs.option.id)
        spec_sku_map[tuple(key)] = s.id
    specs = goods.goodsspecification_set.order_by('id')
    if len(sku_key) < len(specs):
        return
    for index, spec, in enumerate(specs):
        key = sku_key[:]
        options = spec.specificationoption_set.all()
        for option in options:
            key[index] = option.id
            option.sku_id = spec_sku_map.get(tuple(key))

        spec.options = options

    context = {
        'categories': categories,
        'goods': goods,
        'specs': specs,
        'sku': sku,
    }
    logger.info("发送degital[正常][ mobile: %s ]")
    template = loader.get_template('detail.html')
    html_text = template.render(context)
    file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'goods/'+str(sku_id)+'.html')
    with open(file_path, 'w') as f:
        f.write(html_text)

# 商品列表页
@app.task(name='generate_static_list_search_html')
def generate_static_list_search_html():
    categories = get_categories()

    context = {
        'categories': categories
    }

    template = loader.get_template('list.html')
    html_text = template.render(context)

    path_file = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'list.html')

    with open(path_file, 'w') as f:
        f.write(html_text)